<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Redis\CacheDataRedis;
use App\Models\CropsCfg;
use App\Models\Order;
use App\Models\UserCoupon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderCancel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:cancel';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '订单自动取消';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $cancelSeconds = CacheDataRedis::getRedisInstance()->systemConfig('basic.order_cancel_time');
        if (empty($cancelSeconds) || !is_numeric($cancelSeconds) || $cancelSeconds < 60) {
            $cancelSeconds = 60;
        }
        $cancelTime = time() - $cancelSeconds;
        $query      = Order::where('status', 0)->where('created_at', '<=', $cancelTime);
        $query->chunkById(100, function ($list) {
            if (empty($list)) {
                Log::info('没有订单可自动取消');
//                $this->info('====没有订单可自动取消====');
                return false;
            }
            foreach ($list as $item) {
                try {
                    DB::beginTransaction();
                    $this->updateStore($item);
                    Log::info('订单' . $item['id'] . '取消成功');
//                    $this->info('==订单' . $item['id'] . '取消成功==');
                    DB::commit();
                } catch (\Exception $exception) {
                    DB::rollBack();
                }

            }
        });
    }


    public function updateStore($order)
    {
        //更新订单状态
        $order->status    = -1;
        $order->cancel_at = time();
        $order->save();
        //更新商品剩余份数
        $update1 = CropsCfg::where('id', $order['crops_id'])->increment('total', $order['total_num']);
        $update2 = CropsCfg::where('id', $order['crops_id'])->decrement('surplus', $order['total_num']);
        if (!$update1 || !$update2) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('operation_failed'));
        }
        //更新优惠券
        if (!empty($order['rebate_desc'])) {
            $couponInfo = $order['rebate_desc'];
            $result     = UserCoupon::where('id', $couponInfo['id'])->update(['use' => 0]);
            if (!$result) {
                throw new ServiceException(ServiceExceptionConstant::getErrorData('operation_failed'));
            }
        }
    }
}
